package com.zhao.eduservice.service.impl;

import com.zhao.eduservice.entity.EduCourse;
import com.zhao.eduservice.entity.EduCourseDescription;
import com.zhao.eduservice.entity.vo.CourseInfoVo;
import com.zhao.eduservice.entity.vo.CoursePublishVo;
import com.zhao.eduservice.mapper.EduCourseMapper;
import com.zhao.eduservice.service.EduCourseDescriptionService;
import com.zhao.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.servicebase.exceptionhandler.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author test_java
 * @since 2022-10-18
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService courseDescriptionService;


    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        // 1.向课程表添加基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int res = baseMapper.insert(eduCourse);
        if (res <= 0) {
            throw new GuliException(20001, "添加课程失败");
        }

        String cid = eduCourse.getId();

        // 2.向课程简介表添加课程简介
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setId(cid);
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.save(courseDescription);
        return cid;
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        // 查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        // 查询课程表简介表
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);

        BeanUtils.copyProperties(eduCourse,courseInfoVo);
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        // 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int res = baseMapper.updateById(eduCourse);
        if (res <= 0){
            throw new GuliException(20001,"修改课程失败");
        }

        // 修改描述
        EduCourseDescription courseDescription =new EduCourseDescription();
        courseDescription.setId(courseInfoVo.getId());
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(courseDescription);
    }

    @Override
    public CoursePublishVo getPublishCourseInfo(String id) {
        return baseMapper.getPublishCourseInfo(id);
    }
}
